package kr.co.bettersoft.pushchat.fragment;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import kr.co.bettersoft.pushchat.activity.ChatRoomActivity;
import kr.co.bettersoft.pushchat.activity.MemberInfoActivity;
import kr.co.bettersoft.pushchat.activity.PullToRefreshListView;
import kr.co.bettersoft.pushchat.activity.R;
import kr.co.bettersoft.pushchat.activity.PullToRefreshListView.OnRefreshListener;
import kr.co.bettersoft.pushchat.adapter.PushChatChatListAdapter;
import kr.co.bettersoft.pushchat.adapter.PushChatMemberListAdapter;
import kr.co.bettersoft.pushchat.common.CommonConstant;
import kr.co.bettersoft.pushchat.common.CommonUtil;
import kr.co.bettersoft.pushchat.common.PushChatRest;
import kr.co.bettersoft.pushchat.common.SwipeListViewFragment;
import kr.co.bettersoft.pushchat.domain.PushChatChat;
import kr.co.bettersoft.pushchat.domain.PushChatDiary;
import kr.co.bettersoft.pushchat.domain.PushChatFriend;
import kr.co.bettersoft.pushchat.domain.PushChatMember;
import kr.co.bettersoft.pushchat.domain.PushChatUser;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

/**
 * ChattingListFragment
 *  채팅방 리스트 화면
 *   상단 타이틀 : 채팅
 *   왼쪽 섬네일 이미지(없으면 기본 이미지) / 닉네임 / 마지막 대화내용 / 처음 생성되었을때는 채팅방 개설된 날짜. 글 올라오면 마지막 글 올라온 시각. / 메시지 총 개수
 *    새 채팅방은 New 아이콘(들어가지 않은 방) / 확인하지 못한 메시지가 있으면 '새 메시지' 아이콘.
 *     위치는 섬네일 이미지 위에 New   그 줄 끝에 '새메세지'
 * @author blue
 *
 */
public class ChattingListFragment extends SwipeListViewFragment{			
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// 변수

	String TAG = "ChattingListFragment";

	public final int SELECT_CHAT_LIST = 101;  		// 채팅방 목록을 가져온다.		// 
	public final int UPDATE_DEACTIVATE_USER = 102;  		// 채팅방에서 사용자 제거		// updateDeactivateUser


	SharedPreferences sharedPrefCustom;	// 공용 프립스	
	String userId;						// 사용자 아이디

	// 프래그먼트 종료 여부. 종료된 경우 스레드 호출로 인한 에러를 방지하기 위함
	Boolean isFinished = false;

	CommonUtil commonUtil = new CommonUtil();

	// 서버 통신용
	static Boolean countOne = true;		// 한번에 한번만 통신 하도록
	PushChatRest pushChatRest;
	String callResult = "";
	JSONObject jsonObject;

	String resultStr;		// 요청 결과

	// 서버에서 받은 대기 인원 리스트 임시 저장
	int max = 0;

	// 채팅방 리스트.
	List<PushChatChat> pushChatChatRoomEntriesFn;

	// 삭제 - 취소 포지션
	public int cancelPosition;
	boolean needScroll = false;
	// adapter
	private PushChatChatListAdapter pushChatChatListAdapter;		// 그리드뷰 사용할 아답터		

	// 화면 구성
	ListView chatRoomListView;
	View emptyView;				// 데이터 없음 뷰
	ProgressBar pb1;		// 중단 로딩 진행바

	// pull down refresh
	Boolean pullDownRefreshIng  = false;
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	// 핸들러
	Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			try{
				Bundle b = msg.getData();		

				if(b.getInt("showToast")==1){		// 화면에 토스트 띄우기
					Toast.makeText(getActivity(), b.getString("msg"), Toast.LENGTH_SHORT).show();
				}
				if(b.getInt("showAlert")==1){					 // 경고창 . 
					//
					new AlertDialog.Builder(returnThis())
					.setTitle(CommonConstant. alertTitle )                                        
					.setMessage(b.getString("msg"))
					.setIcon(R.drawable.ic_dialog_img)		
					.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							// 단순 확인 용도
						}})
						.setNegativeButton("", null).show();
				}
				if(b.getInt("showChatRoomList")==1){
					// 데이터를 화면에.. 		
					if((pushChatChatRoomEntriesFn!=null)&&(pushChatChatRoomEntriesFn.size()>0)){
						setGriding();			// 항시 업뎃
						chatRoomListView.setVisibility(View.VISIBLE);
						emptyView.setVisibility(View.GONE);
					}else{
						Log.d(TAG,"no data");
						chatRoomListView.setEmptyView(emptyView);
						chatRoomListView.setVisibility(View.GONE);
						emptyView.setVisibility(View.VISIBLE);
					}
				}

				if(b.getInt("confirmAndDelete")==1){					 // 확인받고 대기 취소.
					// 뷰를 보여주도록 하고, 버튼 클릭시 호출 되도록 하기.
					new AlertDialog.Builder(returnThis())
					.setTitle(CommonConstant. alertTitle )                                        
					.setMessage(getResources().getString(R.string.delete_confirm))	// 확인 질문
					.setIcon(R.drawable.ic_dialog_img)		
					.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							handler.sendEmptyMessage(UPDATE_DEACTIVATE_USER);	// 삭제 - 컨트롤러에서 처리
						}})
						.setNegativeButton(android.R.string.no, null).show();
				}

				if(b.getInt("order")==1){
					// 프로그래스바 실행
					pb1.setVisibility(View.VISIBLE);
				}else if(b.getInt("order")==2){
					// 프로그래스바  종료
					pb1.setVisibility(View.GONE);
				}

				switch (msg.what)
				{
				case SELECT_CHAT_LIST : 			// 채팅방 목록을 가져온다.		 
					if(getActivity()!=null) {
						getActivity().runOnUiThread(new RunnableSelectChatList());	 
					}
					break;
				case UPDATE_DEACTIVATE_USER : 			// 채팅방 에서 사용자 삭제
					if(getActivity()!=null) {
						getActivity().runOnUiThread(new RunnableUpdateDeactivateUser());	 
					}
					break;
				default : 
					break;
				}

			}catch(Exception e){
				e.printStackTrace();
			}
		}
	};

	/**
	 * setGriding
	 * 데이터를 화면에 세팅한다
	 *
	 * @param 
	 * @param 
	 * @return 
	 */
	public void setGriding(){
		pushChatChatListAdapter = new PushChatChatListAdapter(getActivity(), this, pushChatChatRoomEntriesFn);
		chatRoomListView.setAdapter(pushChatChatListAdapter);

		//			// 클릭시 채팅방으로
		//			chatRoomListView.setOnItemClickListener(new OnItemClickListener() {
		//				public void onItemClick(AdapterView<?> parent, View v,
		//						int position, long id) {
		//					Intent intent = new Intent(getActivity(), ChatRoomActivity.class);
		//					PushChatChat pushChatChatParam =  pushChatChatRoomEntriesFn.get(position);
		//					intent.putExtra("idChat", pushChatChatParam.getIdChat());			
		//					intent.putExtra("owner", pushChatChatParam.getOwner());			
		//					intent.putExtra("othersNickName", pushChatChatParam.getNickName());			
		//					startActivity(intent);
		//				}	
		//			});

		if(needScroll){
			needScroll = false;
			if(cancelPosition>3){
				chatRoomListView.setSelection(cancelPosition-1);
			}
		}


		//			// item 롱클릭시 
		//			memberListView.setOnItemLongClickListener(new OnItemLongClickListener() {
		//				@Override
		//				public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
		//						int arg2, long arg3) {
		//					if(memberListView.getCount()==pushChatChatRoomEntriesFn.size()){	// 상단에 아무것도 없으므로 그냥 사용
		////						firstEntrancePosition = arg2;
		//					}else{
		////						firstEntrancePosition = arg2 -1;		// 상단에 pull down refresh 영역 한칸 차지하고 있으므로 한칸 빼줌.
		//					}
		////					if(firstEntrancePosition!=0){		// 0 번째는 우선 입장 기능 x. 일반 입장o
		////						confirmAndEnterUser2();
		////					}else{
		////						confirmAndEnterUser();			// 0번째에게는 일반 입장창이라도 뜨게 함. (0번째만 안뜨니 이상해서)
		////					}
		//					return false;
		//				}
		//			});
	}
	//		
	//		


	//	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	//////////////////////////////////////////////////////////////////////////////////////////////////////

	@Override
	public ListView getListView() {
		return chatRoomListView;
	}

	@Override
	public void getSwipeItem(boolean isRight, int position) {
		if(chatRoomListView.getCount()==pushChatChatRoomEntriesFn.size()){	// 상단에 아무것도 없으므로 그냥 사용
			cancelPosition = position;
		}else{
			cancelPosition = position -1;		// 상단에 pull down refresh 영역 한칸 차지하고 있으므로 한칸 빼줌.
		}

		// 밀면 우측 숨겨진 버튼이 보이도록 하기.
		if(isRight){		// 오른쪽으로 밀면 숨김
			pushChatChatRoomEntriesFn.get(cancelPosition).setShowCancelBtnYn(false);
		}else{				// 왼쪽으로 밀면 생김
			pushChatChatRoomEntriesFn.get(cancelPosition).setShowCancelBtnYn(true);
		}
		pushChatChatListAdapter.notifyDataSetChanged();
	}

	@Override
	public void onItemClickListener(ListAdapter adapter, int position) {
		int realChatRoomPosition = 0;
		if(chatRoomListView.getCount()==pushChatChatRoomEntriesFn.size()){	// 상단에 아무것도 없으므로 그냥 사용
			realChatRoomPosition = position;
		}else{
			realChatRoomPosition = position -1;		// 상단에 pull down refresh 영역 한칸 차지하고 있으므로 한칸 빼줌.
		}
		
		
		
		Intent intent = new Intent(getActivity(), ChatRoomActivity.class);
		PushChatChat pushChatChatParam =  pushChatChatRoomEntriesFn.get(realChatRoomPosition);
		intent.putExtra("idChat", pushChatChatParam.getIdChat());			
		intent.putExtra("owner", pushChatChatParam.getOwner());			
		intent.putExtra("otherUserId", pushChatChatParam.getOtherUserId());			
		intent.putExtra("othersNickName", pushChatChatParam.getNickName());			
		startActivity(intent);
	}
	@Override
	public void onItemLongClickListener(ListAdapter adapter, int position) {
		//			if(chatRoomListView.getCount()==pushChatChatRoomEntriesFn.size()){	// 상단에 아무것도 없으므로 그냥 사용
		//				firstEntrancePosition = position;
		//			}else{
		//				firstEntrancePosition = position -1;		// 상단에 pull down refresh 영역 한칸 차지하고 있으므로 한칸 빼줌.
		//			}
		//			if(firstEntrancePosition!=0){		// 0 번째는 우선 입장 기능 x. 일반 입장o
		//				confirmAndEnterUser2();
		//			}else{
		//				confirmAndEnterUser();			// 0번째에게는 일반 입장창이라도 뜨게 함. (0번째만 안뜨니 이상해서)
		//			}
	}

	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	//	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//		
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
		View view = inflater.inflate(R.layout.fragment_chattinglist, null);

		pushChatRest = new PushChatRest();

		chatRoomListView = (ListView) view.findViewById(R.id.chat_room_list_view);		
		emptyView = view.findViewById(R.id.empty1);		// 데이터 없으면 '빈 페이지'(데이터 없음 메시지)표시
		pb1=(ProgressBar) view.findViewById(R.id.progressbar);

		//			// 사용자 아이디를 꺼낸다.
		sharedPrefCustom = getActivity().getSharedPreferences(CommonConstant.prefName,
				Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE);
		userId = sharedPrefCustom.getString("userId", "");


		////////////////////////////////pull down list
		// Set a listener to be invoked when the list should be refreshed.
		((PullToRefreshListView) chatRoomListView).setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				// Do work to refresh the list here.
				if(countOne){
					countOne = false;		
					try {
						pullDownRefreshIng = true;				// 기본 로딩바는 보여주지 않기 위함
						new GetDataTask().execute();
					}catch (Exception e) {
						e.printStackTrace();
					} 
				}else{
					Log.d(TAG,"already running..");		 
					((PullToRefreshListView) chatRoomListView).onRefreshComplete();
				}

			}
		});


		return view;
	}
	//

	//	//////////////////////////////////////////////////////////////////////////////////////////////////////
	// pull down list

	private class GetDataTask extends AsyncTask<Void, Void, String[]> {
		@Override
		protected String[] doInBackground(Void... params) {
			// Simulates a background job.
			Log.d(TAG,"GetDataTask");



			// 파라미터 세팅
			PushChatChat pushChatChatParam = new PushChatChat();
			pushChatChatParam.setMemberId(userId);

			// 서버 메소드 호출
			if(!isFinished){
				callResult = pushChatRest.RestSelectChatList(pushChatChatParam, returnThis());	
				// 결과 처리
				if(!(callResult.equals("F"))){
					//							tempstr = pushChatRest.getTempstr();
					//							pushChatChatRoomEntriesFn = pushChatRest.getPushChatChatEntriesFn();
					try {
						JSONArray jsonArray = new JSONArray(callResult);
						int max = jsonArray.length();

						pushChatChatRoomEntriesFn = new ArrayList<PushChatChat>(max);
						//								pushChatChatEntries = new ArrayList<PushChatChat>(max);

						CommonUtil commonUtil = new CommonUtil();

						Date tempDate = new Date();


						String tmp_idChat = "";
						String tmp_owner = "";
						String tmp_registerDate = "";
						String tmp_nickName = "";
						String tmp_messageCount = "";
						String tmp_readYn = "";
						String tmp_content = "";
						String tmp_recognitionCount = "";
						String tmp_otherUserNickName = "";
						String tmp_thumbnailUrl = "";
						String tmp_otherUserId = "";

						//					Bitmap tmp_profileImage = null;
						Bitmap tmp_thumbnail = null;
						if(max>0){
							for ( int i = 0; i < max; i++ ){
								JSONObject jsonObj = jsonArray.getJSONObject(i);
								try{
									tmp_idChat = jsonObj.getString("idChat");
								}catch(Exception e){
									tmp_idChat = "";
								}
								try{
									tmp_owner = jsonObj.getString("owner");
								}catch(Exception e){
									tmp_owner = "";
								}
								try{
									tmp_registerDate = jsonObj.getString("registerDate");
									// 형변환 작업
									tempDate = commonUtil.sf.parse(tmp_registerDate);
									//											commonUtil.context = contextParam;

									String year = getString(R.string.year);
									String month = getString(R.string.month);
									String day = getString(R.string.day);
									String hour = getString(R.string.hour);
									String minute = getString(R.string.minute);
									SimpleDateFormat sfGeneral = new SimpleDateFormat("yyyy"+year+" MM"+month+" dd"+day+" a hh"+hour+" mm"+minute);
									SimpleDateFormat sfGeneral2 = new SimpleDateFormat("yyyy"+year+" MM"+month+" dd"+day+" HH"+hour+" mm"+minute);
									SimpleDateFormat sfGeneralChat = new SimpleDateFormat("MM"+month+" dd"+day+" a hh"+hour+" mm"+minute);

									tmp_registerDate = sfGeneral.format(tempDate);
								}catch(Exception e){
									tmp_registerDate = "";
								}
								try{
									tmp_nickName = jsonObj.getString("nickName");
								}catch(Exception e){
									tmp_nickName = "";
								}
								try{
									tmp_messageCount = jsonObj.getString("messageCount");
								}catch(Exception e){
									tmp_messageCount = "";
								}
								try{
									tmp_readYn = jsonObj.getString("readYn");
									if(tmp_readYn==null || tmp_readYn.equals("null")){
										tmp_readYn = "";
									}
								}catch(Exception e){
									tmp_readYn = "";
								}
								try{
									tmp_content = jsonObj.getString("content");
									if(tmp_content==null || tmp_content.equals("null")){
										tmp_content = "";
									}
								}catch(Exception e){
									tmp_content = "";
								}
								try{
									tmp_recognitionCount = jsonObj.getString("recognitionCount");
								}catch(Exception e){
									tmp_recognitionCount = "";
								}
								try{
									tmp_otherUserNickName = jsonObj.getString("otherUserNickName");
								}catch(Exception e){
									e.printStackTrace();
									tmp_otherUserNickName = "";
								}
								try{
									tmp_otherUserId = jsonObj.getString("otherUserId");
								}catch(Exception e){
									e.printStackTrace();
									tmp_otherUserId = "";
								}
								try{
									tmp_thumbnailUrl = jsonObj.getString("thumbnailUrl");
									if(tmp_thumbnailUrl==null||tmp_thumbnailUrl.length()<1||tmp_thumbnailUrl.equals("null")){
										tmp_thumbnail = null;
										//								tmp_thumbnail = getResoucres().getDrawable(R.drawable.ic_launcher);
									}else{
										//								tmp_thumbnail = null;
										tmp_thumbnail = LoadImage(tmp_thumbnailUrl);
										tmp_thumbnail = commonUtil.getRoundedCornerBitmap(tmp_thumbnail);	// 라운딩 처리
									}
								}catch(Exception e){
									tmp_thumbnailUrl = "";
									tmp_thumbnail = null;
								}
								pushChatChatRoomEntriesFn.add(new PushChatChat(
										tmp_idChat,
										tmp_owner,
										tmp_registerDate,
										tmp_nickName,
										tmp_messageCount,
										tmp_content,
										tmp_recognitionCount,
										tmp_otherUserId,
										tmp_otherUserNickName,
										tmp_thumbnailUrl,
										tmp_thumbnail,
										tmp_readYn
								));
							}
						}
					}catch (JSONException e) {
						e.printStackTrace();
					}
					//							pushChatChatEntriesFn = pushChatChatEntries; 

					Log.d(TAG,"pushChatChatRoomEntriesFn size:"+pushChatChatRoomEntriesFn.size());

					for(int i=0; i<pushChatChatRoomEntriesFn.size(); i++){
						if(pushChatChatRoomEntriesFn.get(i).getThumbnail() == null){
							BitmapDrawable default_bd = (BitmapDrawable) getResources().getDrawable((R.drawable.empty_member));
							Bitmap default_bmp = default_bd.getBitmap();
							default_bmp = commonUtil.getRoundedCornerBitmap(default_bmp);	// 라운딩 처리
							pushChatChatRoomEntriesFn.get(i).setThumbnail(default_bmp);
						}
					}

				}
				showChatRoomList();
			}

			countOne = true;		// 다시 호출 되도록 수정..	
			return null;
		}
		@Override
		protected void onPostExecute(String[] result) {
			// Call onRefreshComplete when the list has been refreshed.
			pullDownRefreshIng = false;							// 기본 로딩바 보여주기 상태 초기화. resume 기능으로는 보여지도록.
			((PullToRefreshListView) chatRoomListView).onRefreshComplete();		// 리프레시가 끝났음을....
			super.onPostExecute(result);
		}
	}



	/**
	 * 멤버 리스트를 보여준다
	 * showChatRoomList
	 */
	public void showChatRoomList(){
		if(getActivity()!=null){
			getActivity().runOnUiThread(new Runnable(){		 
				@Override
				public void run(){
					Message message = handler.obtainMessage();				
					Bundle b = new Bundle();
					b.putInt("showChatRoomList", 1);
					message.setData(b);
					handler.sendMessage(message);
				}
			});
		}
	}
	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	/**
	 * confirmAndDelete
	 *  확인 후 삭제
	 *
	 * @param msg
	 * @param
	 * @return 
	 */
	public void confirmAndDelete(){
		if(getActivity()!=null){
			getActivity().runOnUiThread(new Runnable(){		 
				@Override
				public void run(){
					Message message = handler.obtainMessage();				
					Bundle b = new Bundle();
					b.putInt("confirmAndDelete", 1);
					message.setData(b);
					handler.sendMessage(message);
				}
			});
		}
	}

	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


	/**
	 * 러너블. 채팅방 목록을 가져온다.		
	 */
	class RunnableSelectChatList implements Runnable {
		public void run(){
			new backgroundThreadSelectChatList().execute();
		}
	}
	/**
	 * backgroundThreadSelectChatList
	 * 비동기 스레드  채팅방 목록을 가져온다.
	 * @author blue
	 *
	 */
	public class backgroundThreadSelectChatList extends AsyncTask<Void, Void, Void>{
		@Override protected void onPostExecute(Void result) {  
		} 
		@Override protected void onPreExecute() {  
		} 
		@Override protected Void doInBackground(Void... params) {  
			Log.d(TAG,"backgroundThreadSelectChatList");

			// 파라미터 세팅
			PushChatChat pushChatChatParam = new PushChatChat();
			pushChatChatParam.setMemberId(userId);

			// 서버 메소드 호출
			if(FragmentHome.restCallCntUp()){
				showPb();
				if(!isFinished){
					callResult = pushChatRest.RestSelectChatList(pushChatChatParam, returnThis());	
					// 결과 처리
					if(!(callResult.equals("F"))){
						//							tempstr = pushChatRest.getTempstr();
						//							pushChatChatRoomEntriesFn = pushChatRest.getPushChatChatEntriesFn();
						try {
							JSONArray jsonArray = new JSONArray(callResult);
							int max = jsonArray.length();

							pushChatChatRoomEntriesFn = new ArrayList<PushChatChat>(max);
							//								pushChatChatEntries = new ArrayList<PushChatChat>(max);

							CommonUtil commonUtil = new CommonUtil();

							Date tempDate = new Date();


							String tmp_idChat = "";
							String tmp_owner = "";
							String tmp_registerDate = "";
							String tmp_nickName = "";
							String tmp_messageCount = "";
							String tmp_readYn = "";
							String tmp_content = "";
							String tmp_recognitionCount = "";
							String tmp_otherUserNickName = "";
							String tmp_thumbnailUrl = "";
							String tmp_otherUserId = "";

							//					Bitmap tmp_profileImage = null;
							Bitmap tmp_thumbnail = null;
							if(max>0){
								for ( int i = 0; i < max; i++ ){
									JSONObject jsonObj = jsonArray.getJSONObject(i);
									try{
										tmp_idChat = jsonObj.getString("idChat");
									}catch(Exception e){
										tmp_idChat = "";
									}
									try{
										tmp_owner = jsonObj.getString("owner");
									}catch(Exception e){
										tmp_owner = "";
									}
									try{
										tmp_registerDate = jsonObj.getString("registerDate");
										// 형변환 작업
										tempDate = commonUtil.sf.parse(tmp_registerDate);
										//											commonUtil.context = contextParam;

										String year = getString(R.string.year);
										String month = getString(R.string.month);
										String day = getString(R.string.day);
										String hour = getString(R.string.hour);
										String minute = getString(R.string.minute);
										SimpleDateFormat sfGeneral = new SimpleDateFormat("yyyy"+year+" MM"+month+" dd"+day+" a hh"+hour+" mm"+minute);
										SimpleDateFormat sfGeneral2 = new SimpleDateFormat("yyyy"+year+" MM"+month+" dd"+day+" HH"+hour+" mm"+minute);
										SimpleDateFormat sfGeneralChat = new SimpleDateFormat("MM"+month+" dd"+day+" a hh"+hour+" mm"+minute);

										tmp_registerDate = sfGeneral.format(tempDate);
									}catch(Exception e){
										tmp_registerDate = "";
									}
									try{
										tmp_nickName = jsonObj.getString("nickName");
									}catch(Exception e){
										tmp_nickName = "";
									}
									try{
										tmp_messageCount = jsonObj.getString("messageCount");
									}catch(Exception e){
										tmp_messageCount = "";
									}
									try{
										tmp_readYn = jsonObj.getString("readYn");
										if(tmp_readYn==null || tmp_readYn.equals("null")){
											tmp_readYn = "";
										}
									}catch(Exception e){
										tmp_readYn = "";
									}
									try{
										tmp_content = jsonObj.getString("content");
										if(tmp_content==null || tmp_content.equals("null")){
											tmp_content = "";
										}
									}catch(Exception e){
										tmp_content = "";
									}
									try{
										tmp_recognitionCount = jsonObj.getString("recognitionCount");
									}catch(Exception e){
										tmp_recognitionCount = "";
									}
									try{
										tmp_otherUserNickName = jsonObj.getString("otherUserNickName");
									}catch(Exception e){
										e.printStackTrace();
										tmp_otherUserNickName = "";
									}
									try{
										tmp_otherUserId = jsonObj.getString("otherUserId");
									}catch(Exception e){
										e.printStackTrace();
										tmp_otherUserId = "";
									}
									try{
										tmp_thumbnailUrl = jsonObj.getString("thumbnailUrl");
										if(tmp_thumbnailUrl==null||tmp_thumbnailUrl.length()<1||tmp_thumbnailUrl.equals("null")){
											tmp_thumbnail = null;
											//								tmp_thumbnail = getResoucres().getDrawable(R.drawable.ic_launcher);
										}else{
											//								tmp_thumbnail = null;
											tmp_thumbnail = LoadImage(tmp_thumbnailUrl);
											tmp_thumbnail = commonUtil.getRoundedCornerBitmap(tmp_thumbnail);	// 라운딩 처리
										}
									}catch(Exception e){
										tmp_thumbnailUrl = "";
										tmp_thumbnail = null;
									}
									pushChatChatRoomEntriesFn.add(new PushChatChat(
											tmp_idChat,
											tmp_owner,
											tmp_registerDate,
											tmp_nickName,
											tmp_messageCount,
											tmp_content,
											tmp_recognitionCount,
											tmp_otherUserId,
											tmp_otherUserNickName,
											tmp_thumbnailUrl,
											tmp_thumbnail,
											tmp_readYn
									));
								}
							}
						}catch (JSONException e) {
							e.printStackTrace();
						}
						//							pushChatChatEntriesFn = pushChatChatEntries; 

						Log.d(TAG,"pushChatChatRoomEntriesFn size:"+pushChatChatRoomEntriesFn.size());

						for(int i=0; i<pushChatChatRoomEntriesFn.size(); i++){
							if(pushChatChatRoomEntriesFn.get(i).getThumbnail() == null){
								BitmapDrawable default_bd = (BitmapDrawable) getResources().getDrawable((R.drawable.empty_member));
								Bitmap default_bmp = default_bd.getBitmap();
								default_bmp = commonUtil.getRoundedCornerBitmap(default_bmp);	// 라운딩 처리
								pushChatChatRoomEntriesFn.get(i).setThumbnail(default_bmp);
							}
						}

					}
					showChatRoomList();
				}
				hidePb();		// @@ 
				FragmentHome.restCallCntDown();
			}
			countOne = true;		// 다시 호출 되도록 수정..	
			return null; 
		}
	}
	/**
	 * 러너블. 채팅방 에서 사용자 삭제	
	 */
	class RunnableUpdateDeactivateUser implements Runnable {
		public void run(){
			new backgroundThreadUpdateDeactivateUser().execute();
		}
	}
	/**
	 * backgroundThreadUpdateDeactivateUser
	 * 비동기 스레드  채팅방 에서 사용자 삭제	
	 * @author blue
	 *
	 */
	public class backgroundThreadUpdateDeactivateUser extends AsyncTask<Void, Void, Void>{
		@Override protected void onPostExecute(Void result) {  
		} 
		@Override protected void onPreExecute() {  
		} 
		@Override protected Void doInBackground(Void... params) {  
			Log.d(TAG,"backgroundThreadUpdateDeactivateUser");

			// 파라미터 세팅	// 내 정보? 채팅방 정보.
			PushChatUser pushChatUserParam = new PushChatUser();
			pushChatUserParam.setMemberId(userId);
			pushChatUserParam.setPushChatChatIdChat(pushChatChatRoomEntriesFn.get(cancelPosition).getIdChat());
			pushChatUserParam.setPushChatChatOwner(pushChatChatRoomEntriesFn.get(cancelPosition).getOwner());
			//				Log.d(TAG,"cancelPosition:"+cancelPosition);
			//				Log.d(TAG,"PushChatChatIdChat:"+pushChatChatRoomEntriesFn.get(cancelPosition).getIdChat());
			//				Log.d(TAG,"PushChatChatOwner:"+pushChatChatRoomEntriesFn.get(cancelPosition).getOwner());
			// 서버 메소드 호출
			if(FragmentHome.restCallCntUp()){
				showPb();
				if(!isFinished){
					callResult = pushChatRest.RestUpdateDeactivateUser(pushChatUserParam);	
					FragmentHome.restCallCntDown();
					// 결과 처리
					if(callResult.equals("SUCCESS")){
						// 알림창 띄우고 리스트 새로 고침
						needScroll = true;
						handler.sendEmptyMessage(SELECT_CHAT_LIST);		// 전체 목록 불러오기 
						showResultDialog(getResources().getString(R.string.delete_success));
					}else{
						// 알림창 띄움
						showResultDialog(getResources().getString(R.string.delete_fail));
					}
				}
				hidePb();		// @@ 

			}
			countOne = true;		// 다시 호출 되도록 수정..	
			return null; 
		}
	}


	//	///////////////////////////////////////////////////////////////////////////////////////////////////////

	// 이미지 처리
	/**
	 * LoadImage
	 *  이미지 URL 에서 이미지 받아온 스트림을 비트맵으로 저장한다
	 *
	 * @param $imagePath
	 * @param
	 * @return bm
	 */
	private Bitmap LoadImage( String $imagePath ) {
		InputStream inputStream = OpenHttpConnection( $imagePath ) ;
		Bitmap bm = BitmapFactory.decodeStream( inputStream ) ;
		return bm;
	}
	/**
	 * OpenHttpConnection
	 *  이미지 URL 에서 이미지 받아와서 스트림으로 저장한다
	 *
	 * @param $imagePath
	 * @param
	 * @return stream
	 */
	private InputStream OpenHttpConnection(String $imagePath) {
		// TODO Auto-generated method stub
		InputStream stream = null ;
		try {
			URL url = new URL( $imagePath ) ;
			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection() ;
			urlConnection.setRequestMethod( "GET" ) ;
			urlConnection.connect() ;
			if( urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK ) {
				stream = urlConnection.getInputStream() ;
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			Log.d(TAG,"OpenHttpConnection-"+$imagePath);
			Log.w(TAG,"MalformedURLException");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.w(TAG,"IOException");
		}
		return stream ;
	}




	////////////////////////	Util	///////////////////////////////////////////////////////////////////////	

	/**
	 * returnThis
	 *  컨택스트 리턴한다
	 *
	 * @param
	 * @param
	 * @return
	 */
	public Context returnThis(){
		return getActivity();
	}

	/*
	 * 핸들러를 통한 작업.
	 */
	/**
	 * showMsg
	 *  화면에 토스트 띄움 msg 변수에 내용을 넣어서 호출하면 화면에 토스트를 띄운다.
	 *
	 * @param msg
	 * @param
	 * @return
	 */
	public void showMsg(final String msg){		
		if(getActivity()!=null){
			getActivity().runOnUiThread(new Runnable(){	 
				@Override
				public void run(){
					Message message = handler.obtainMessage();				
					Bundle b = new Bundle();
					b.putInt("showToast", 1);
					b.putString("msg", msg);
					message.setData(b);
					handler.sendMessage(message);
				}
			});
		}
	} 

	/**
	 * showResultDialog
	 *  얼럿 띄운다
	 *
	 * @param msg
	 * @param
	 * @return 
	 */
	public void showResultDialog(final String msg){
		if(getActivity()!=null){
			getActivity().runOnUiThread(new Runnable(){	 
				@Override
				public void run(){
					Message message = handler.obtainMessage();				
					Bundle b = new Bundle();
					b.putInt("showAlert", 1);
					b.putString("msg", msg);			// 화면에 보여줄 메시지
					message.setData(b);
					handler.sendMessage(message);
				}
			});
		}
	}
	// 확인을 받는 컨펌 창을 띄운다
	/**
	 * showConfirmDialog
	 *  확인을 받는 컨펌 창을 띄운다
	 *
	 * @param showConfirmCode
	 * @param msg
	 * @return 
	 */
	public void showConfirmDialog(final int showConfirmCode, final String msg){
		if(getActivity()!=null){
			getActivity().runOnUiThread(new Runnable(){		 
				@Override
				public void run(){
					Message message = handler.obtainMessage();				
					Bundle b = new Bundle();
					b.putInt("showConfirm", showConfirmCode);		 
					b.putString("msg", msg);			// 화면에 보여줄 메시지
					message.setData(b);
					handler.sendMessage(message);
				}
			});
		}
	}

	// 중앙 프로그래스바 보임, 숨김
	/**
	 * showPb
	 *  중앙 프로그래스바 가시화한다
	 *
	 * @param
	 * @param
	 * @return
	 */
	public void showPb(){
		new Thread( 
				new Runnable(){
					public void run(){
						Message message = handler .obtainMessage();
						Bundle b = new Bundle();
						b.putInt( "order" , 1);
						message.setData(b);
						handler .sendMessage(message);
					}
				}
		).start();
	}
	/**
	 * hidePb
	 *  중앙 프로그래스바 비가시화한다
	 *
	 * @param
	 * @param
	 * @return
	 */
	public void hidePb(){
		new Thread(
				new Runnable(){
					public void run(){
						Message message = handler .obtainMessage();
						Bundle b = new Bundle();
						b.putInt( "order" , 2);
						message.setData(b);
						handler .sendMessage(message);
					}
				}
		).start();
	}

	/**
	 * onResume
	 *  액티비티 리쥼시 닫기 카운터초기화한다
	 *
	 * @param
	 * @param
	 * @return
	 */
	@Override
	public void onResume(){
		super.onResume();
		isFinished = false;
		FragmentHome.app_end = 0;

		if(countOne){
			countOne = false;		
			handler.sendEmptyMessage(SELECT_CHAT_LIST);		// 전체 목록 불러오기 
		}else{
			Log.d(TAG,"already running..");		 
		}
	}
	@Override
	public void onDestroy(){
		isFinished = true;
		super.onDestroy();
	}
}